package solo

import (
	"hundsun.com/hsl/hschain/consensus/common"
	"hundsun.com/hsl/hschain/consensus/impl/solo/checker"
	"hundsun.com/hsl/hschain/consensus/impl/solo/miner"
	"hundsun.com/hsl/hschain/consensus/types"
	"hundsun.com/hsl/hschain/module"
	"hundsun.com/hsl/hschain/module/registry"
	protosconfig "hundsun.com/hsl/hschain/protos/config"
)

func init() {
	common.RegConsensus(types.ConsensusTypeSolo, NewSolo)
}

// Module solo共识模块
type Module struct {
	module.Adapter
	types.ConsensusStatus

	miner   *miner.SoloMiner
	checker *checker.SoloChecker

	baseClient *common.BaseClient
}

// NewSolo 新建一个Solo模块
func NewSolo() common.ConsensusModule {
	m := &Module{}
	m.baseClient = common.NewBaseClient()
	m.miner = miner.NewMiner(m.GetBaseClient())
	m.checker = checker.NewChecker(m.GetBaseClient())
	moduleStartupFunc := func(startedInterestedModules map[string][]*registry.ModRegKV) error {
		conType := m.baseClient.GetCurParam().GetConsensus().GetType()
		switch conType {
		case protosconfig.SoloConsensusType:
			m.baseClient.StartEventLoop()
			m.miner.Start(m.RootCtx, m.Config, m.Log)
			m.checker.Start(m.RootCtx, m.Config, m.Log)
			m.baseClient.SetCurrentCon(m)
			m.baseClient.SetModuleCfg(m.Config)
		case protosconfig.DposConsensusType:

		}
		return nil
	}

	m.baseClient.InitParam()
	m.Init(module.ConsensusModuleName, nil, moduleStartupFunc)
	return m
}

// IsMasterStandbyMode 主备状态校验
func (m *Module) IsMasterStandbyMode() bool {
	return false
}

// Shutdown ...
func (m *Module) Shutdown() (module.Status, error) {
	m.RootCtxCancelFunc()
	return module.StatusDown, nil
}

// GetBaseClient get 公共Client
func (m *Module) GetBaseClient() *common.BaseClient {
	return m.baseClient
}

// SetBaseClient set 公共Client
func (m *Module) SetBaseClient(client *common.BaseClient) {
	m.baseClient = client
}
